package edu.mti.csi.amaml.xml;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.xml.sax.SAXException;

/**
 * eXtensible Stylesheet Language Transformations Transformer.
 * Transforms XML documents to output documents using XSLT stylesheets.
 *
 */
public class XSLTTransformer
{
	/**
	 * Transforms an XML document to specified output document using the specified XSLT stylesheet.
	 * @param xmlPath Path of the XML document to transform.
	 * @param xsltPath Path of the XSLT stylesheet to use.
	 * @param params key-value pairs passed to XSLT stylesheet.
	 * @param outputPath Path of the output document.
	 * @throws FileNotFoundException
	 * @throws TransformerException
	 * @throws SAXException
	 * @throws IOException
	 * @throws ParserConfigurationException
	 */
	public static void transform(String xmlPath, String xsltPath, String[][] params, String outputPath) throws FileNotFoundException, TransformerException, SAXException, IOException, ParserConfigurationException
	{
		Transformer t = TransformerFactory.newInstance().newTransformer(new StreamSource(xsltPath));
		
		for (int i = 0 ; i < params.length ; i ++)
		{
			t.setParameter(params[i][0], params[i][1]);
		}
		
		t.transform(new DOMSource(DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(xmlPath)), new StreamResult(new FileOutputStream(outputPath)));
	}
}
